package com.yc.io;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;

// 不同的文件拷贝方式
public class JavaCopyFile {

	public static void main(String[] args) throws Exception{
		String sourcePath = "";
		String destPath = "";
		File source = new File(sourcePath);
		File dest = new File(destPath);

		// copy file conventional way using Stream
		long start1 = System.nanoTime();
		copyFileUsingStream(source, dest);
		long end1 = System.nanoTime();
		System.out.println(end1 - start1);

		// copy file using java.nio FileChannel
		long start2 = System.nanoTime();
		copyFileUsingChannel(source, dest);
		long end2 = System.nanoTime();
		System.out.println(end2 - start2);
	}


	// using java 7 or higher copy files
	private static void copyFielUsingJavaAbove7Files(File source, File dest) throws IOException {
		Files.copy(source.toPath(), dest.toPath());
	}

	// using apache commons io
	private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
		FileUtils.copyFile(source, dest);
	}

	// 创建InputStream和OutputStream 进行java 复制文件
	private static void copyFileUsingStream (File source, File dest) throws IOException {
		InputStream is = null; // 输入流
		OutputStream os = null; // 输出流
		try {
			is = new FileInputStream(source);
			os = new FileOutputStream(dest);

			byte[]  buffer =  new byte[1024];
			int length ;
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}

	// Java NIO 通过FileChannel中transferFrom复制文件，比stream更快、
	private static void copyFileUsingChannel(File source, File dest) throws IOException {
		FileChannel sourceChannel = null;
		FileChannel destChannel = null;
		try {
			sourceChannel = new FileInputStream(source).getChannel();
			destChannel = new FileOutputStream(dest).getChannel();
			destChannel.transferFrom(sourceChannel, 0 , sourceChannel.size());
		} finally {
			if (sourceChannel != null) {
				sourceChannel.close();
			}
			if (destChannel != null) {
				destChannel.close();
			}
		}
	}
}
